package com.markyao.service.db.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.markyao.mapper.ConfigInfoMapper;
import com.markyao.mapper.HisConfigInfoMapper;
import com.markyao.recos.conf.RecosConfService;
import com.markyao.recos.regist.RecosRegistConfig;
import com.markyao.service.db.AbstractConfigService;
import com.markyao.service.db.ConfigInfoService;
import com.markyao.service.raft.BroadcastConfigInfoService;
import com.markyao.service.raft.BroadcastService;
import com.markyao.utils.SnowflakeIdGenerator;
import com.markyao.vo.ConfigInfoVo;
import com.markyao.vo.PageVo;
import com.markyao.vo.QueryParams;
import com.markyao.vo.Result;
import com.markyao.vo.pojo.ConfigInfo;
import com.markyao.vo.pojo.HisConfigInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.beans.factory.config.YamlProcessor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.yaml.snakeyaml.Yaml;

import java.nio.charset.StandardCharsets;
import java.util.*;

import static com.markyao.utils.ResovleConfigUtils.*;
@Service
public class ConfigInfoServiceImpl extends AbstractConfigService implements ConfigInfoService {
    @Autowired
    ConfigInfoMapper configInfoMapper;
    @Autowired
    HisConfigInfoMapper hisConfigInfoMapper;
    @Autowired
    SnowflakeIdGenerator idGenerator;
    @Autowired
    @Qualifier("refreshConfAdviceSet")
    Map<String,Object> refreshConfAdviceSet;
    @Autowired
    RecosRegistConfig recosRegistConfig;

    @Override
    public Result insert(ConfigInfoVo configInfov) {
        ConfigInfo configInfo = abscopy(configInfov);
        long id = idGenerator.generateId();
        configInfo.setId(id);
        int insert = configInfoMapper.insert(configInfo);
//        boolean f=broadcastConfigInfoService.insertConfigInfo(configInfov);
        return Result.success("插入成功!",insert);
    }

    @Transactional
    @Override
    public Result delete(Long id) {
        int insert=insert2his(id);
        if (insert>0){
            int delete = configInfoMapper.delete(id);
//            boolean f=broadcastConfigInfoService.deleteConfigInfo(id);
            return Result.success("删除成功",delete);
        }
        return Result.failed(500,"版本未插入成功");
    }

    @Override
    @Transactional
    public Result deletes(String[] ids) {
        int insert=insert2hisBatch(ids);
        if (insert>0){
            int delete=configInfoMapper.deleteBatch(ids);
            if (delete>0){
//                boolean f=broadcastConfigInfoService.deleteConfigInfos(ids);
                return Result.success("删除成功",delete);
            }
        }
        return Result.failed(500,"删除失败");
    }

    private int insert2hisBatch(String[] ids) {
        List<ConfigInfo>configInfoList=configInfoMapper.selectByIds(ids);
        List<HisConfigInfo>hisConfigInfoList=copy2HisList(configInfoList);
        int insert=hisConfigInfoMapper.insertBatch(hisConfigInfoList);
        return insert;
    }

    private List<HisConfigInfo> copy2HisList(List<ConfigInfo> configInfoList) {
        List<HisConfigInfo>hisConfigInfoList=new ArrayList<>(configInfoList.size());
        for (ConfigInfo configInfo : configInfoList) {
            HisConfigInfo hisConfigInfo=new HisConfigInfo();
            BeanUtils.copyProperties(configInfo,hisConfigInfo);
            long generateId = idGenerator.generateId();
            hisConfigInfo.setId(generateId);
            hisConfigInfoList.add(hisConfigInfo);
        }
        return hisConfigInfoList;
    }

    private int insert2his(Long id){
        ConfigInfo configInfo = configInfoMapper.selectById(id);
        HisConfigInfo hisConfigInfo=new HisConfigInfo();
        BeanUtils.copyProperties(configInfo,hisConfigInfo);
        long generateId = idGenerator.generateId();
        hisConfigInfo.setId(generateId);
        int insert=hisConfigInfoMapper.insert(hisConfigInfo);
        return insert;
    }

    @Override
    @Transactional
    public Result update(ConfigInfoVo configInfov) {
        Long id = Long.parseLong(configInfov.getId());
        int insert = insert2his(id);
        if (insert>0){
            ConfigInfo abscopy = abscopy(configInfov);
            //更新新版本的日期
            abscopy.setGmtModified(new Date());
            abscopy.setGmtCreate(new Date());
            int update = configInfoMapper.update(abscopy);
            //通知更新
            boolean f=adviceRefresh(configInfov);
            if (f){
//                boolean b=broadcastConfigInfoService.updateConfigInfo(configInfov);
                return Result.success("更新成功",update);
            }
        }
        return Result.failed(500,"版本未插入成功");

    }


    @Override
    public ConfigInfoVo select(QueryParams queryParams) {
        if (queryParams.getId()!=null){
            ConfigInfo configInfo = configInfoMapper.selectById(Long.parseLong(queryParams.getId()));
            return abscopy(configInfo);
        }
        return new ConfigInfoVo();
    }
    @Override
    public Result selectList(QueryParams queryParams) {
        List<ConfigInfo>configInfoList=null;
        StringBuilder querySql=new StringBuilder("WHERE ");
        int cnt=0;
        if (StringUtils.hasText(queryParams.getDataId())){
            querySql.append("data_id =#{queryParam.dataId}");
            cnt++;
        }
        if(StringUtils.hasText(queryParams.getGroupId())){
            if (cnt==0){
                querySql.append("group_id = #{queryParam.groupId}");
            }else {
                querySql.append("AND group_id = #{queryParam.groupId}");
            }
            cnt++;
        }
        if (StringUtils.hasText(queryParams.getAppName())){
            if (cnt==0){
                querySql.append("app_name = #{queryParam.appName}");
            }else {
                querySql.append("AND app_name = #{queryParam.appName}");
            }
            cnt++;
        }
        PageHelper.startPage(queryParams.getCurrentPage(),queryParams.getPageSize());
        if (cnt==0){
            configInfoList=configInfoMapper.selectList();
        }else {
            configInfoList=configInfoMapper.selectByQuerySql(queryParams,querySql.toString());
        }

        if (configInfoList==null){
            return Result.success("配置列表为空",null);
        }
        PageInfo pageInfo=new PageInfo(configInfoList);
        PageVo pageVo=new PageVo();
        pageVo.setTotal(pageInfo.getTotal());
        List<ConfigInfoVo> configInfoVos = abscopyList(configInfoList);
        pageVo.setList(configInfoVos);
        return Result.success(pageVo);
    }

    @Override
    public Map<String, Object> selectByDataIdAndGroupId(String dataId, String groupId) {
        if (groupId==null || groupId.length()==0){
            groupId="DEFAULT GROUP";
        }
        String content=configInfoMapper.selectByDataIdAndGroupId(dataId,groupId);
        if(!StringUtils.hasText(content)){
            return null;
        }
        Map<String, Object> map=null;
        if (isYml(dataId)){
            map=resovleYml(content);
        }else {
            map=resovleProps(content);

        }
        return map;
    }





}
